<template>
    <div>
        <PageTitle title="场次编辑"></PageTitle>
        <div v-if="isFirst" style="display: flex; justify-content: center; margin-bottom: 20px; padding: 10px 0;">
            <Steps :current="1" style="width: 400px;">
                <Step title="商品详情"></Step>
                <Step title="场次票品"></Step>
            </Steps>
        </div>
        <div class="concert-wrap">
            <div class="concert-left">
                <div class="title">场次</div>
                <div class="cells">
                    <div class="cell" v-for="(item, index) in concerts" :key="index" :class="{'active': activeIndex === index}" @click="handleSwitchConcert(index)">
                        <Badge v-if="item.is_error" status="error" />
                        <div class="label" title="双击编辑">{{ item.name }}</div>
                        <Dropdown trigger="click" @on-click="handleClickDropdown($event, index)">
                            <div class="icon-more">
                                <Icon type="ios-more" :size="18" color="#a1a1a1" />
                            </div>
                            <DropdownMenu slot="list">
                                <DropdownItem name="copy">复制</DropdownItem>
                                <DropdownItem name="rename">重命名</DropdownItem>
                                <DropdownItem name="remove">删除</DropdownItem>
                            </DropdownMenu>
                        </Dropdown>
                    </div>
                </div>
                <div class="add-btn">
                    <Button type="info" long @click="handleShowConcert">增加场次</Button>
                </div>
            </div>
            <div v-if="concerts.length === 0" class="concert-body">
                <div class="no-data">请先添加场次</div>
            </div>
            <div v-else class="concert-body">
                <Divider orientation="left">
                    <span style="font-weight: bold;">场次基础信息</span>
                </Divider>
                <Form ref="form" :model="form" :label-width="120">
                    <!-- <FormItem label="场次类型：" required>
                        <RadioGroup v-model="form.is_multiple" style="vertical-align: top;">
                            <Radio :label="0" style="vertical-align: top;">单场次</Radio>
                            <Radio :label="1" style="vertical-align: top;">多场次</Radio>
                        </RadioGroup>
                    </FormItem> -->
                    <FormItem required :error="showFormErr ? '请选择演出时间' : ''">
                        <template slot="label">
                            <Tooltip content="票品抖音自动核销时间=演出结束时间+25小时" placement="right" :transfer=true max-width="220">
                                <Icon type="ios-help-circle" color="red" size="14"></Icon>
                            </Tooltip>
                            <span>演出时间：</span>
                        </template>
                        <DatePicker v-model="form.times" type="datetimerange" :options="disableDateOptions" format="yyyy-MM-dd HH:mm" placeholder="选择演出时间" style="width: 260px"></DatePicker>
                    </FormItem>
                    <FormItem required :error="showFormErr ? '请选择演出时间' : ''">
                        <template slot="label">
                            <span>备票截止：</span>
                        </template>
                        <DatePicker v-model="form.delivery_end_at" type="datetime" :options="disableDateOptions" format="yyyy-MM-dd HH:mm" placeholder="选择备票结束时间" style="width: 260px"></DatePicker>
                    </FormItem>
                    <FormItem label="冻结规则：">
                        <div>
                            <Table :columns="freeze_rules_columns" :data="form.freeze_rules" border style="width: 720px;">
                                <template slot-scope="{ row, index }" slot="freeze_times">
                                    <DatePicker v-model="form.freeze_rules[index].times" type="datetimerange" format="yyyy-MM-dd HH:mm" placeholder="请选择时间区间" style="width: 100%;" transfer></DatePicker>
                                </template>
                                <template slot-scope="{ row, index }" slot="freeze_type">
                                    <RadioGroup style="width: 100%;" v-model="form.freeze_rules[index].type">
                                        <Radio :label="1">固定金额</Radio>
                                        <Radio :label="2">固定比例</Radio>
                                    </RadioGroup>
                                </template>
                                <template slot-scope="{ row, index }" slot="freeze_value">
                                    <InputNumber
                                        v-if="form.freeze_rules[index].type == 1"
                                        :min="0"
                                        :precision="2"
                                        style="width: 100%;"
                                        v-model="form.freeze_rules[index].value"
                                        :formatter="value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                        :parser="value => value.replace(/\$\s?|(,*)/g, '')"></InputNumber>
                                    <InputNumber
                                        v-else
                                        :min="0"
                                        :precision="1"
                                        style="width: 100%;"
                                        v-model="form.freeze_rules[index].value"
                                        :formatter="value => `${value}%`"
                                        :parser="value => value.replace('%', '')"></InputNumber>
                                </template>
                                <template slot-scope="{ row, index }" slot="freeze_delete">
                                    <Button type="error" size="small" @click="handleDeleteFreezeRules(index)">删除</Button>
                                </template>
                            </Table>
                            <Button type="info" ghost style="margin-top: 10px;" @click="handleAddFreezeRules">增加规则</Button>
                        </div>
                    </FormItem>

                    <FormItem required label="发货规则：">
                        <div>
                            <Table :columns="delivery_rules_columns" :data="form.delivery_rules" border style="width: 640px;">
                                <template slot-scope="{ row, index }" slot="delivery_times">
                                    <DatePicker v-model="form.delivery_rules[index].times" type="datetimerange" format="yyyy-MM-dd HH:mm" placeholder="请选择时间区间" style="width: 100%;" transfer></DatePicker>
                                </template>
                                <template slot-scope="{ row, index }" slot="delivery_type">
                                    <RadioGroup v-model="form.delivery_rules[index].type">
                                        <Radio :label="1">寄回平台</Radio>
                                        <Radio :label="2">自配送</Radio>
                                        <Radio :label="3">现场取票</Radio>
                                    </RadioGroup>
                                </template>
                                <template slot-scope="{ row, index }" slot="delivery_delete">
                                    <Button type="error" size="small" @click="handleDeleteDeliveryRules(index)">删除</Button>
                                </template>
                            </Table>
                            <Button type="info" ghost style="margin-top: 10px;" @click="handleAddDeliveryRules">增加规则</Button>
                        </div>
                    </FormItem>
                </Form>
                <div style="overflow: hidden;">
                    <Divider orientation="left">
                        <span style="font-weight: bold;">场次票品信息</span>
                    </Divider>
                </div>
                <div>
                    <Table :columns="columns" :data="skus" border>
                        <template slot-scope="{ row, index }" slot="name">
                            <Input v-model="skus[index].name" style="width: 100%;" />
                        </template>
                        <template slot-scope="{ row, index }" slot="price">
                            <InputNumber v-model="skus[index].price" :min="0.01" :precision="2" :active-change="false" style="width: 100%;" />
                        </template>
                        <template slot-scope="{ row, index }" slot="service_fee_type">
                            <RadioGroup v-model="skus[index].service_fee_type">
                                <Radio :label="1">固定金额</Radio>
                                <Radio :label="2">固定比例</Radio>
                            </RadioGroup>
                        </template>
                        <template slot-scope="{ row, index }" slot="service_fee">
                            <InputNumber
                                v-if="skus[index].service_fee_type == 1"
                                :min="0"
                                :precision="2"
                                style="width: 100%;"
                                v-model="skus[index].service_fee"
                                :formatter="value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                :parser="value => value.replace(/\$\s?|(,*)/g, '')"></InputNumber>
                            <InputNumber
                                v-else
                                :min="0"
                                :precision="1"
                                style="width: 100%;"
                                v-model="skus[index].service_fee"
                                :formatter="value => `${value}%`"
                                :parser="value => value.replace('%', '')"></InputNumber>
                        </template>
                        <template slot-scope="{ row, index }" slot="packs">
                            <InputNumber v-model="skus[index].packs" :min="1" :step="1" :precision="0" :active-change="false" style="width: 100%;" />
                        </template>
                        <template slot-scope="{ row, index }" slot="max_number">
                            <InputNumber v-model="skus[index].max_number" :min="1" :step="1" :precision="0" :active-change="false" style="width: 100%;" />
                        </template>
                        <template slot-scope="{ row, index }" slot="stocks">
                            <InputNumber v-model="skus[index].stocks" disabled :min="0" :step="1" :precision="0" :active-change="false" style="width: 100%;" />
                        </template>
                        <template slot-scope="{ row, index }" slot="sale_status">
                            <i-switch v-model="skus[index].sale_status" :trueValue="1" :falseValue="0" size="large">
                                <span slot="open">正常</span>
                                <span slot="close">售罄</span>
                            </i-switch>
                        </template>
                        <template slot-scope="{ row, index }" slot="sale_partner">
                            <Select v-model="skus[index].sale_partner_id" :transfer=true filterable clearable style="width: 100%">
                                <Option v-for="item in partnerLists" :value="item.id" :key="item.id">{{ item.name }}</Option>
                            </Select>
                        </template>
                        <template slot-scope="{ row, index }" slot="delete">
                            <Poptip :transfer=true width="400" placement="left">
                                <PoptipTable :data="stockData" :columns="stockColumn" slot="content"></PoptipTable>
                                <Button type="primary" size="small" style="margin-right: 10px;" @click="handleShowStocks(row)">库存</Button>
                            </Poptip>
                            <Button type="error" size="small" @click="handleDeleteTicket(index)">删除</Button>
                        </template>
                    </Table>
                    <Button type="info" ghost style="margin-top: 10px;" @click="handleAddTicket">增加票档</Button>
                </div>
            </div>
        </div>
        <div style="margin-top: 20px;">
            <Button type="default" :disabled="submiting" @click="handleBack" style="margin-right: 7px;">取消</Button>
            <Button type="primary" :loading="submiting" @click="handleSubmit">提交</Button>
        </div>
        <Spin size="large" fix v-if="isLoading"></Spin>
        
        <Modal
            v-model="showAddModal"
            :title="addForm.index !== null ? '编辑场次' : '新增场次'"
            width="360px"
            @on-ok="handleCreateConcert"
            @on-cancel="handleCancelConcert"
        >
            <Input ref="input" v-model="addForm.name" placeholder="请输入场次名称"></Input>
        </Modal>
    </div>
</template>

<script>
const orgSku = { id: '', name: '', price: null, service_fee_type: 1, service_fee: 0, packs: 1, max_number: 6, sale_status: 1 };
const orgFreezeRule = { times: '', type: 1, value: 0 }
const orgDeliveryRule = { times: '', type: 1 }
import {formatDate, deepClone} from '@/libs/tools.js';
import PoptipTable from '@/components/utils/poptip-table.vue';
export default {
    components: {
        PoptipTable
    },
    data() {
        return {
            freeze_rules_columns: [
                {
                    title: '时间段',
                    width: 290,
                    slot: 'freeze_times'
                },
                {
                    title: '类型',
                    slot: 'freeze_type'
                },
                {
                    title: '冻结值',
                    width: 120,
                    slot: 'freeze_value'
                },
                {
                    title: '操作',
                    width: 68,
                    slot: 'freeze_delete'
                }
            ],
            delivery_rules_columns: [
                {
                    title: '时间段',
                    width: 290,
                    slot: 'delivery_times'
                },
                {
                    title: '类型',
                    slot: 'delivery_type'
                },
                {
                    title: '操作',
                    width: 68,
                    slot: 'delivery_delete'
                }
            ],
            stockColumn: [
                {
                    title: '总库存',
                    key: 'stocks'
                },
                {
                    title: '直售库存',
                    key: 'stocks_direct'
                },
                {
                    title: '代拍库存',
                    key: 'stocks_agent'
                }
            ],
            stockData: [],
            partnerLists: [],
            project_id: null,
            isLoading: false,
            isFirst: false,
            showAddModal: false,
            showFormErr: false,
            submiting: false,
            activeIndex: null,
            addForm: {
                index: null,
                name: ''
            },
            form: {
                is_multiple: 0,
                times: [],
                delivery_end_at: '',
                freeze_rules: [],
                delivery_rules: [],
            },
            concerts: [],
            skus: [],
            columns: [
                {
                    title: '票档名称',
                    slot: 'name'
                },
                {
                    title: '价格',
                    slot: 'price'
                },
                {
                    title: '服务费收取方式',
                    slot: 'service_fee_type',
                },
                {
                    slot: 'service_fee',
                    renderHeader: (h, params) => {
                        return h('div', [
                            h('Tooltip', {
                                props: {
                                    content: '无服务费请填写固定金额0',
                                    placement: 'right',
                                    transfer: true,
                                    maxWidth: '220',
                                },
                                class: 'm-tooltip-overflow'
                            }, [
                                h('span', '服务费'),
                                h('Icon', {
                                    props: {
                                        type: 'ios-help-circle',
                                        color: "red",
                                        size: '14'
                                    },
                                    style: {
                                        marginRight: '2px'
                                    }
                                })
                                
                            ])
                        ]);
                    }
                },
                {
                    slot: 'packs',
                    renderHeader: (h, params) => {
                        return h('div', [
                            h('Tooltip', {
                                props: {
                                    content: '大于1视为套票',
                                    placement: 'right',
                                    transfer: true,
                                    maxWidth: '220',
                                },
                                class: 'm-tooltip-overflow'
                            }, [
                                h('span', '票品数量'),
                                h('Icon', {
                                    props: {
                                        type: 'ios-help-circle',
                                        color: "red",
                                        size: '14'
                                    },
                                    style: {
                                        marginRight: '2px'
                                    }
                                })
                                
                            ])
                        ]);
                    }
                },
                {
                    title: '最大购买数量',
                    slot: 'max_number'
                },
                {
                    title: '售卖状态',
                    slot: 'sale_status'
                },
                {
                    title: '售卖服务商',
                    slot: 'sale_partner',
                },
                {
                    title: '操作',
                    width: 120,
                    slot: 'delete'
                }
            ],
            specs: [
            	{
            		name: '',
            		value: [],
            		imgs: [],
            		options: [],
            		shadows: []
            	}
            ],
            skus: [],
            disableDateOptions: {
                disabledDate (date) {
                    return date && date.valueOf() < Date.now() - 86400000;
                }
            }
        }
    },
    mounted() {
        const id = this.$route.query.id;
        if(!id) {
            this.$Message.error({
                content: '获取商品ID失败',
                onClose: () => {
                    this.$router.back();
                }
            })
        }
        this.project_id = id;
        this.form.freeze_rules.push(deepClone(orgFreezeRule))
        this.form.delivery_rules.push(deepClone(orgDeliveryRule))
        this.init();
    },
    methods: {
        init() {
            // 获取商品详情及场次信息
            this.isLoading = true;
            this.$ajax.get('/project/read/'+this.project_id).then(res=>{
                if(res.concerts && res.concerts.length > 0) {
                    this.concerts = res.concerts.map(item => {
                        let freeze_rules = item.freeze_rules || [];
                        let delivery_rules = item.delivery_rules || [];
                        let concert = {
                            id: item.id,
                            name: item.name,
                            times: [item.start_at, item.end_at],
                            delivery_end_at: item.delivery_end_at,
                            freeze_rules: freeze_rules.map(item => {
                                return {
                                    times: [item.start_at, item.end_at],
                                    type: Number(item.type),
                                    value: parseFloat(item.value)
                                }
                            }),
                            delivery_rules: delivery_rules.map(item => {
                                return {
                                    times: [item.start_at, item.end_at],
                                    type: Number(item.type)
                                }
                            }),
                            is_multiple: item.is_multiple,
                            is_error: false,
                            skus: []
                        }
                        res.skus.forEach(sku => {
                            if(sku.concert_id === item.id) {
                                concert.skus.push({
                                    id: sku.id,
                                    name: sku.name,
                                    price: parseFloat(sku.price),
                                    service_fee_type: sku.service_fee_type,
                                    service_fee: parseFloat(sku.service_fee),
                                    packs: sku.packs,
                                    max_number: sku.max_number,
                                    sale_status: sku.sale_status,
                                    sale_partner_id: sku.sale_partner_id,
                                    stocks: sku.stocks,
                                    stocks_direct: sku.stocks_direct,
                                    stocks_agent: sku.stocks_agent
                                });
                            }
                        })
                        return concert;
                    })
                    this.$nextTick(() => {
                        this.handleSwitchConcert(0);
                    })
                }else{
                    this.isFirst = true;
                }
                this.isLoading = false;
            }).catch(err => {
                this.$Message.error(err.message || '加载详情失败');
            })
            //获取服务商
            this.$ajax.get('/partner/index', {
                params: {
                    pageSize: 1000
                }
            }).then(res => {
                this.partnerLists = res.items
            }).catch(err => {})
        },
        handleShowStocks(row) {
            let obj = {
                stocks: row.stocks,
                stocks_direct: row.stocks_direct,
                stocks_agent: row.stocks_agent,
            }
            this.stockData = [obj];
        },
        // 点击场次下拉菜单
        handleClickDropdown(type, index) {
            if(type === 'rename') {
                this.addForm.index = index;
                this.addForm.name = this.concerts[index]['name'];
                this.handleShowConcert();
            }else if(type === 'copy') {
                // 保存上一次操作的内容
                this.handleSavePrev();
                // 执行复制
                const concert = deepClone(this.concerts[index]);
                this.concerts.splice(index + 1, 0, {
                    name: concert.name + ' 复制',
                    times: concert.times,
                    delivery_end_at: concert.delivery_end_at,
                    freeze_rules: concert.freeze_rules,
                    delivery_rules: concert.delivery_rules,
                    is_multiple: concert.is_multiple,
                    is_error: false,
                    skus: concert.skus.map(item => {
                        item.id = '';
                        return item;
                    })
                })
                this.$forceUpdate();
                setTimeout(() => {
                    this.handleSwitchConcert(index + 1);
                }, 50)
            }else if(type === 'remove') {
                this.$Modal.confirm({
                    title: '删除场次',
                    content: '<p>场次删除后不可恢复，是否确认删除？</p>',
                    onOk: () => {
                        this.activeIndex = null;
                        this.concerts.splice(index, 1);
                        const len = this.concerts.length;
                        if(index >= len) {
                            index = len - 1;
                            if(index < 0) {
                                index = null;
                            }else if(index === 0 && len === 0) {
                                index = null;
                            }
                        }
                        this.handleSwitchConcert(index);
                    }
                });
            }
        },
        // 打开场次编辑
        handleShowConcert() {
            this.showAddModal = true;
            this.$nextTick(() => {
                this.$refs.input.focus();
            })
        },
        // 创建/编辑场次
        handleCreateConcert() {
            const { index, name } = this.addForm;
            this.showAddModal = false;
            if(!name) return false;
            if (index !== null) {
                this.concerts[index]['name'] = name;
                return false;
            }
            this.concerts.push({
                name: name,
                times: [],
                delivery_end_at: '',
                freeze_rules: [],
                delivery_rules: [],
                is_multiple: 0,
                is_error: false,
                skus: [deepClone(orgSku)]
            })
            this.$nextTick(() => {
                this.handleSwitchConcert(this.concerts.length - 1)
            })
        },
        handleCancelConcert() {
            this.showAddModal = false;
            setTimeout(() => {
                this.addForm.index = null;
                this.addForm.name = '';
            }, 310)
        },
        // 添加票品
        handleAddTicket() {
            this.skus.push(deepClone(orgSku))
        },
        // 删除票品
        handleDeleteTicket(index) {
            this.skus.splice(index, 1);
        },
        // 切换场次
        handleSwitchConcert(index, unsave) {
            if(this.activeIndex === index) return false;
            if(this.activeIndex !== null && !unsave) {
                // 保存上一次操作的内容
                this.handleSavePrev();
            }
            const concert = this.concerts[index];
            this.skus = deepClone(concert.skus);
            this.form.is_multiple = concert.is_multiple;
            this.form.delivery_end_at = concert.delivery_end_at;
            this.form.freeze_rules = concert.freeze_rules;
            this.form.delivery_rules = concert.delivery_rules;
            this.form.times = concert.times;
            this.activeIndex = index;
        },
        // 保存上一次操作的内容
        handleSavePrev() {
            const i = this.activeIndex;
            // 没有数据时不作后续操作
            if(i === null || this.concerts.length === 0) return false;
            const { form, skus } = this;
            this.concerts[i]['times'] = form.times;
            this.concerts[i]['delivery_end_at'] = form.delivery_end_at;
            this.concerts[i]['freeze_rules'] = form.freeze_rules;
            this.concerts[i]['delivery_rules'] = form.delivery_rules;
            this.concerts[i]['is_multiple'] = form.is_multiple;
            this.concerts[i]['skus'] = deepClone(skus);
        },
        // 提交
        handleSubmit() {
            const { form } = this;
            // 校验当前表单的演出时间
            this.showFormErr = false;
            if(!form.times[0]) {
                this.showFormErr = true;
                return false;
            }
            // 保存上一次操作的内容
            this.handleSavePrev();
            // 对数据进行提交前的校验
            this.concerts = this.concerts.map(item => {
                // 校验演出时间
                if(!item.times[0]) {
                    item.is_error = true;
                    return item;
                }
                // 校验票品
                for(let i = 0; i < item.skus.length; i++) {
                    const sku = item.skus[i];
                    if(!sku.name || sku.price === null) {
                        item.is_error = true;
                        return item;
                    }
                }
                item.is_error = false;
                return item;
            })
            // 校验
            const isErr = this.concerts.findIndex(item => item.is_error);
            if(isErr !== -1) {
                this.$Message.error('请完善场次基本信息和票品信息');
                return false;
            }
            // 格式化为提交需要的参数
            let params = {
                project_id: this.project_id,
                concerts: this.concerts.map(item => {
                    let concert = {
                        name: item.name,
                        start_at: formatDate(item.times[0], 'yyyy-MM-dd hh:mm'),
                        end_at: formatDate(item.times[1], 'yyyy-MM-dd hh:mm'),
                        delivery_end_at: formatDate(item.delivery_end_at, 'yyyy-MM-dd hh:mm'),
                        freeze_rules: item.freeze_rules.map(item => {
                            return {
                                start_at: formatDate(item.times[0], 'yyyy-MM-dd hh:mm'),
                                end_at: formatDate(item.times[1], 'yyyy-MM-dd hh:mm'),
                                type: item.type,
                                value: item.value,
                            }
                        }),
                        delivery_rules: item.delivery_rules.map(item => {
                            return {
                                start_at: formatDate(item.times[0], 'yyyy-MM-dd hh:mm'),
                                end_at: formatDate(item.times[1], 'yyyy-MM-dd hh:mm'),
                                type: item.type,
                            }
                        }),
                        is_multiple: item.is_multiple,
                        skus: item.skus
                    }
                    if(item.id) {
                        concert.id = item.id;
                    }
                    return concert;
                })
            }
            this.submiting = true;
            this.$ajax.post('/project/concert/set', params).then(res => {
                this.$Message.success({
                    content: "提交成功",
                    onClose: () => {
                        this.handleBack();
                    }
                })
            }).catch(err => {
                this.$Message.error(err.message || '提交失败');
                this.submiting = false;
            })
        },
        // 添加规则
        handleAddFreezeRules() {
            this.form.freeze_rules.push(deepClone(orgFreezeRule))
        },
        // 删除规则
        handleDeleteFreezeRules(index) {
            this.form.freeze_rules.splice(index, 1);
        },
        // 添加规则
        handleAddDeliveryRules() {
            this.form.delivery_rules.push(deepClone(orgDeliveryRule))
        },
        // 删除规则
        handleDeleteDeliveryRules(index) {
            this.form.delivery_rules.splice(index, 1);
        },
        handleBack() {
            this.$router.back();
        }
    }
}
</script>

<style lang="less">
.concert-wrap {
	display: flex;
    border-radius: 3px;
    border: 1px solid #e8eaec;
    .concert-left {
        flex-shrink: 0;
        width: 220px;
        border-right: 1px solid #e8eaec;
        background-color: #f9f9f9;
        .title {
            padding: 10px 15px;
            line-height: 20px;
            font-size: 14px;
            font-weight: bold;
            background-color: #e8eaec;
        }
        .cell {
            display: flex;
            align-items: center;
            padding: 15px;
            border-bottom: 1px solid #e8eaec;
            cursor: pointer;
            .ivu-badge {
                line-height: 32px;
            }
            .label {
                flex: 1;
                min-width: 1px;
                font-size: 14px;
                line-height: 22px;
                color: #787878;
            }
            .icon-more {
                flex-shrink: 0;
                margin-left: 10px;
                width: 22px;
                text-align: center;
                line-height: 22px;
                cursor: pointer;
            }
        }
        .active {
            margin-right: -1px;
            background-color: #fff;
            .label {
                color: #333;
            }
        }
        .add-btn {
            padding: 10px 20px;
        }
    }
    .concert-body {
        flex: 1;
        padding: 20px;
        min-width: 1px;
        .no-data {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #999;
        }
    }
}
</style>